
require('./tuoguan.scss');

var ProvCitySelector = require("COMMON/Components/ProvCitySelect/v1.0/");

var PaginationX = require("COMMON/modules/pagination-x/v1.0");
var PaginationY = require("COMMON/modules/pagination-x");

var loading = require('COMMON/js/util.loading.pc.js');

var Toast = require('COMMON/modules/Toast');
var toast = new Toast; 

var ParseTemplate = ZFT.Util.ParseTemplate;
var Template = {
    buildings: ParseTemplate(require("./tpl/addcontract_buildings.xtpl")),
    building: ParseTemplate(require("./tpl/addcontract_building.xtpl")),
    house: ParseTemplate(require("./tpl/addcontract_house.xtpl")),
    select: ParseTemplate(require("./tpl/select.xtpl"))
};

var Main = ZFT.Util.Class({
    container: "",
    PAGE_SIZE: 15,

    dom: {
        search: {
            province: '#searchProvince',
            city: '#searchCity',
            district: '#searchDistrict',
            name: '#searchInp',
            btn: '#searchBtn'
        },
        tbody: {
            buildings: '#tbodyBuildings',
            building: '#tbodyBuilding',
            house: '#tbodyHouse',
            rate: '#tbodyRate'
        },
        building: '#building',
        rule: {
            container: '#rule',
            tbody: '#tbodyRuleEdit',
            btn: {
                add: '#btnAddRatio',
                edit: '#btnEditRule'
            },
            input: {
                rate: '#inpRate',
                ratio: '#inpRatio'
            },
            settle_type: '#settleType',
            money: '#money',
            begin_time: '#beginDate',
            end_time: '#endDate',
            billing_day: '#billingDay'
        },
        pagination: {
            buildings: ".paginationWrapBuildings",
            building: ".paginationWrapBuilding"
        }
    },
    pagination: {
        buildings: null,
        building: null
    },
    ajaxUrls: {
        getBuildings: '/r/Building_getTrustBuilding',
        getBuilding: '/r/Building_getHouseByBuildingId',
        saveContract: '/r/Trust_addTrustInfo'
    },

    xhrGetBuildings: null,  // 获取楼宇XHR对象
    xhrGetBuilding: null,   // 获取房源XHR对象
    xhrSaveContract: null,

    locationSelect: null,  // 省市联动实例对象

    ruleInited: false,

    selectedHouse: null,

    init: function () {
        var _this = this;
        this.searchParam = {
            province: $("#searchProvince").val(),
            city: $("#searchCity").val(),
            country: ($("#searchDistrict").val() == 0) ? 0 : $("#searchDistrict :selected").text(),
            name: $("#searchInp").val(),
            page: 1,
            page_size: this.PAGE_SIZE
        }
        this.ajaxGetBuildings(_this.searchParam);

        if (!Array.indexOf) {
            Array.prototype.indexOf = function (el) {
                for (var i = 0, n = this.length; i < n; i++) {
                    if (this[i] === el) {
                        return i;
                    }
                }
                return -1;
            }
        }

        this.locationSelect = new ProvCitySelector({
            provId: this.dom.search.province,                    //参数为<select></select>省标签的id
            cityId: this.dom.search.city,                        //参数为<select></select>市标签的id
            onProvChange: function (provId) {
                _this.ajaxRenderDistrict();                //当省下拉框变化时执行的回调函数，参数为 省下拉框中 所选省份对应的省份代号
            },
            onCityChange: function (cityId) {                    //当省下拉框变化时执行的回调函数，参数为 市下拉框中 所选城市对应的城市代号
                _this.ajaxRenderDistrict(cityId);
            },
            afterLoading: function () {
                _this.ajaxRenderDistrict($(_this.dom.search.city).val());
            }
        });
        this.ajaxRenderDistrict();

        $(this.dom.tbody.buildings).on('click', '.btn-viewbuilding', function () {
            _this.ajaxGetBuilding({
                id: $(this).attr('data-id'),
                page: 1,
                page_size: _this.PAGE_SIZE
            });

            _this.selectedHouse = null;
            $(_this.dom.rule.container).hide();
        });

        $(this.dom.tbody.building).on('click', ':checkbox', function () {
            if ($(this).is(':checked')) {
                _this.addHouse(this);
            } else {
                _this.deleteHouse(this);
            }
        });

        $(this.dom.rule.container).on('click', this.dom.rule.btn.add, function () {
            var rate = $.trim($(_this.dom.rule.input.rate).val()),
                ratio = $.trim($(_this.dom.rule.input.ratio).val()),
                r = /^[0-9]{1,2}$/,
                rateArr = $(_this.dom.rule.tbody).find('td:first-child').children('input').map(function () { return this.value; }).get();

            if ((r.test(rate) || rate == 100) && (r.test(ratio) || ratio == 100) && rateArr.indexOf(rate) == -1) {
                $(_this.dom.rule.tbody).append('<tr><td><input class="input t-center" value="' + rate + '"> %</td><td><input class="input t-center" value="' + ratio + '"> %</td></tr>');
            } else {
                ZFT.Util.STip("fail", "出租率不能与现有相同,并且分成比例不超过100", 5000);
            }

            $(_this.dom.rule.input.rate).val('');
            $(_this.dom.rule.input.ratio).val('');
        }).on('click', this.dom.rule.btn.edit, function () {

            _this.ajaxSaveRule();

        });

        $(this.dom.search.btn).on('click', function () {
            _this.ajaxGetBuildings(_this.searchParam);
        });
         $("body").on('click', '.cancel,.close', function (e) {
            _this.closeModal(e);
        })
    },

    ajaxRenderData: function (opts) {
        return ZFT.Util.Ajax(opts.url, {
            type: 'POST',
            params: opts.params,
            loading: function () {
                var loadingOpts = {};

                loadingOpts.id = opts.loading.id;
                loadingOpts.text = opts.loading.text || '';
                loadingOpts.className = opts.loading.className;
                loadingOpts.tag = opts.loading.tag || '';
                if (opts.loading.tag == 'td' || opts.loading.tag == 'tr') {
                    loadingOpts.colspan = opts.loading.colspan ? opts.loading.colspan : '';
                }

                var html = loading(opts.loading.text, loadingOpts);
                $(opts.container).html(html);
            },
            success: function (res) {
                $('#' + opts.loading.id).remove();


                if (res.code == 200 || res.code == 'success') {
                    opts.success && opts.success(res);
                } else {

                    opts.error && opts.error(res);
                }
            },
            serverError: function (xhr, txt) {

            }
        })
    },

    ajaxSendData: function (opts) {
        /*
            opts: {
                url:
                params:
                loading: {
                    text
                }
                success: fn
            }
         */
        return ZFT.Util.Ajax(opts.url, {
            type: 'POST',
            params: opts.params,
            loading: function () {
                toast.show('loading', opts.loading.text);
            },
            success: function (res) {
                toast.hide();

                if (res.code == 200) {
                    opts.success && opts.success(res);
                } else {
                    ZFT.Util.STip('fail', res.msg);
                    opts.error && opts.error(res);
                }
            },
            serverError: function (xhr, txt) {
                // ZFT.Util.STip( txt );
            }
        })
    },

    ajaxRenderDistrict: function (cityid) {
        if (!cityid) {
            $(this.dom.search.district).html('<option value="0">请选择</option>');
            return false;
        }

        var _this = this;

        ZFT.Util.Ajax('/index/getCountry.html', {
            type: 'POST',
            params: {
                city_id: cityid
            },
            success: function (res) {
                var html = '<option value="0">请选择</option>';
                if (res.code == 200) {
                    html += Template.select({ data: res.data.list });
                    $(_this.dom.search.district).prop({ disabled: false });
                    $(_this.dom.search.district).html(html);
                } else {
                    $(_this.dom.search.district).prop({ disabled: true });
                }
            },
            serverError: function (xhr, txt) {
                // ZFT.Util.STip( txt );
            }
        })
    },

    ajaxGetBuildings: function (params) {
        var _this = this;

        this.xhrGetBuildings = this.ajaxRenderData({
            container: this.dom.tbody.buildings,
            url: this.ajaxUrls.getBuildings,
            params: params,
            loading: {
                id: 'buildingsLoading',
                text: '正在努力加载楼宇列表...',
                className: 'tb-loading',
                colspan: 7,
                tag: 'td'
            },
            success: function (res) {

                var param = params;

                _this.renderBuildings(res.data.list);

                if (_this.pagination.buildings) {

                    _this.pagination.buildings.render({ current: res.data.current_page, total: res.data.total });

                } else {

                    _this.pagination.buildings = new PaginationX({
                        container: $(_this.dom.pagination.buildings),
                        count: 7,
                        showTotal: true,
                        jump: true,
                        filter: true
                    });

                    _this.pagination.buildings.on("page.switch", function (toPage, current, total) {
                        var page_size = $(".paginationWrapBuildings").attr("data-size");
                        _this.searchParam.page = toPage;
                        _this.searchParam.page_size = page_size ? page_size : 15;
                        _this.xhrGetBuildings.readyState == 4 && _this.ajaxGetBuildings(_this.searchParam);

                    });

                    _this.pagination.buildings.render({ current: res.data.current_page, total: res.data.total });

                }
            },
            error: function (res) {
                $(_this.dom.tbody.buildings).html('<tr><td colspan="7" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        })
    },

    renderBuildings: function (data) {
        // "id":1,//楼宇编号
        // "name":"哈哈1",//楼宇名称
        // "province":1,//省份
        // "city":1,//市
        // "country":1,//区
        // "address":"六铺炕",//楼宇地址
        // "building_number":30,//楼宇栋数(业主查询没有这个字段)
        // "building_count":2,//房源数量
        for (var i = 0, len = data.length; i < len; i++) {
            data[i].city = this.locationSelect.getCity(data[i].province, data[i].city);
            data[i].province = this.locationSelect.getProvince(data[i].province);
        }

        var html = Template.buildings({ data: data });
        $(this.dom.tbody.buildings).html(html);
    },

    ajaxGetBuilding: function (params) {
        var _this = this;

        $(this.dom.building).show();

        this.xhrGetBuilding = this.ajaxRenderData({
            container: this.dom.tbody.building,
            url: this.ajaxUrls.getBuilding,
            params: params,
            loading: {
                id: 'buildingLoading',
                text: '正在努力加载房源列表...',
                className: 'tb-loading',
                colspan: 6,
                tag: 'td'
            },
            success: function (res) {

                var param = params;

                _this.renderBuilding(res.data.list, param.id);

                if (_this.pagination.building) {

                    _this.pagination.building.render({ current: res.data.current_page, total: res.data.total });

                } else {

                    _this.pagination.building = new PaginationY({
                        container: $(_this.dom.pagination.building),
                        count: 7,
                        showTotal: true,
                        jump: true,
                    });

                    _this.pagination.building.on("page.switch", function (toPage, current, total) {
                        var page_size = $(".paginationWrap").attr("data-size");
                        param.page = toPage;
                        _this.params.page_size = page_size ? page_size : 15;
                        _this.xhrGetBuilding.readyState == 4 && _this.ajaxGetBuilding(param);

                    });

                    _this.pagination.building.render({ current: res.data.current_page, total: res.data.total });

                }
            },
            error: function (res) {
                $(_this.dom.tbody.building).html('<tr><td colspan="6" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        })
    },

    renderBuilding: function (data, buildid) {

        // for( var i=0, len = data.length; i < len; i++ ) {
        //     data[i].city = this.locationSelect.getCity( data[i].province, data[i].city );
        //     data[i].province = this.locationSelect.getProvince( data[i].province );
        // }

        var html,
            pers=ZFT.Util.getPermission();
            data["chckPer"]=($.inArray("40",pers)!==-1) ? 1 : 0;
            console.log(data["chckPer"],pers)
        html = Template.building({ data: data, buildid: buildid });

        $(this.dom.tbody.building).html(html);
    },

    addHouse: function (target) {
        var _this = this;
        //   console.log(target);
        // 保存以下参数:
        // building    是   int     楼宇ID
        // house   是   string  房源编号数组 '12345,123445,123456'
        // owner_id    是   int     业主ID
        // mobile  是   string  业主电话

        if (this.selectedHouse) {
            if (this.selectedHouse.owner_id == $(target).attr('data-mid')) {
                this.selectedHouse.house.push($(target).attr('data-houseid'));
            } else {
                ZFT.Util.STip('fail', '一份合同只能设置一个业主');
                $(target).prop('checked', false);
            }
        } else {
            this.selectedHouse = {};
            this.selectedHouse.building = $(target).attr('data-buildid');
            this.selectedHouse.house = [$(target).attr('data-houseid')];
            this.selectedHouse.owner_id = $(target).attr('data-mid');
            this.selectedHouse.mobile = $(target).attr('data-mobile');

            this.initRule();
        }

        // console.log( this.selectedHouse );
        /*
                 this.xhrGetHouse = this.ajaxSendData({
                     url: this.ajaxUrls.getHouse,
                     params: {
                        id: houseId
                    },
                     loading: {
                         text: '获取房源信息...'
                     },
                     success: function( res ) {
                         $( _this.dom.house ).show();
                         _this.renderHouse( res.data, buildid );
                     },
                     error: function( res ) {
                         $( _this.dom.tbody.house ).append( '<tr><td colspan="6" align="center" class="tb-nodata">房源编号' + houseId + ':' + res.msg + '</td></tr>' );
                     }
                 })*/
    },

    deleteHouse: function (houseId) {

        this.selectedHouse.house.splice(this.selectedHouse.house.indexOf(houseId), 1);

        if (!this.selectedHouse.house.length) {
            this.selectedHouse = null;
            $(this.dom.rule.container).hide();
        }

        //   console.log(this.selectedHouse);
        // $( this.dom.tbody.house ).children('tr').filter(function(){
        //     return $(this).find(':checkbox').attr('data-houseId') == houseId;
        // }).remove();

    },

    renderHouse: function (data, buildid) {
        // var trs = $( this.dom.tbody.house ).children('tr').filter(function(){
        //         return $(this).find(':checkbox').attr('data-mid') == data.mid;
        //     }),
        //     html,
        //     isChecked = false;


        // if( trs.length ) {

        //     isChecked = trs.eq(0).find(':checkbox').prop('checked');
        //     html = Template.house({ data: data, buildid: buildid, checked: isChecked });
        //     trs.after( html );

        // } else {

        //     html = Template.house({ data: data, buildid: buildid, checked: isChecked });
        //     $( this.dom.tbody.house ).append( html );

        // }
    },

    initRule: function () {
        $(this.dom.rule.container).show();
        // this.dom.rule.settle_type
        $(this.dom.rule.money).val('');
        $(this.dom.rule.begin_time).val('');
        $(this.dom.rule.end_time).val('');
        $(this.dom.rule.tbody).empty();

        if (!this.ruleInited) {
            $('#beginDate').datepicker({
                format: "yyyymmdd",
                maxViewMode: 2,
                language: "zh-CN",
                autoclose: true
            });

            $('#endDate').datepicker({
                format: "yyyymmdd",
                maxViewMode: 2,
                language: "zh-CN",
                autoclose: true
            });
            //this.initDate();
            this.ruleInited = true;
        }

    },
    ajaxSaveRule: function () {
        var ruleParams = {};
        var _this = this;
        var reg=/^[1-9]\d*$/;
        ruleParams.rate_arr = $(this.dom.rule.tbody).children('tr').map(function () {
            var rental = $(this).find('input').eq(0).val(),
                split = $(this).find('input').eq(1).val();
            return {
                rental: rental,
                split: split
            }
        }).get();
        ruleParams.settle_type = $(this.dom.rule.settle_type).val();
        ruleParams.money = $(this.dom.rule.money).val();
        ruleParams.begin_time = $(this.dom.rule.begin_time).val();
        ruleParams.end_time = $(this.dom.rule.end_time).val();
        ruleParams.billing_day = $.trim($(this.dom.rule.billing_day).val());


        if (!ruleParams.rate_arr.length) {
            ZFT.Util.STip('fail', '输入出租率/业主分成比例后务必点击添加按钮');
            return false;
        }
        if ($.trim(ruleParams.money) == '') {
            ZFT.Util.STip('fail', '保底金额不能为空');
            return false;
        }
        if ($.trim(ruleParams.begin_time) == '') {
            ZFT.Util.STip('fail', '请选择托管起始日期');
            return false;
        }
        if ($.trim(ruleParams.end_time) == '') {
            ZFT.Util.STip('fail', '请选择托管截止日期');
            return false;
        }
        if (reg.test(ruleParams.billing_day)) {
            if(ruleParams.billing_day>28){
                return ZFT.Util.STip('fail', '账单日应在每月28日之前');
            }
        }else{
            ZFT.Util.STip('fail', '账单日输入有误');
            return false;
        }

        var param = $.extend({}, ruleParams, this.selectedHouse);

        param.house = param.house.join();
        param.rate_arr = JSON.stringify(param.rate_arr);
        this.xhrSaveContract = this.ajaxSendData({
            url: this.ajaxUrls.saveContract,
            params: param,
            loading: {
                text: '保存规则...'
            },
            success: function (res) {
                // type,content,duration,callback
                toast.show('success', res.msg, 2000, function () {
                    console.log('跳转写这边');
                    window.location.href = '/index/index/tuoguanjiesuan'
                });

            },
            error: function (res) {

            }
        })
    },
    //暂时不用
    /*initDate: function () {
        var _this = this;
            billing_day = $(_this.dom.rule.billing_day);
        billing_day.datepicker({
            format: "mmdd",
            startView: 1,
            maxViewMode: 1,
            language: "zh-CN",
            autoclose: true
        });
        $(_this.dom.rule.settle_type).on("change", function (e) {
            var type = $(e.currentTarget).val();
            billing_day.datepicker('destroy');
            if (type == 1) {
                billing_day.datepicker({
                    format: "mmdd",
                    startView: 1,
                    maxViewMode: 1,
                    language: "zh-CN",
                    autoclose: true
                }).val("");
            } else {
                billing_day.datepicker({
                    format: "dd",
                    maxViewMode: 0,
                    language: "zh-CN",
                    autoclose: true
                }).val("");
            }

        })
    },*/

    //关闭模态框
    closeModal: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".m-modal_bg").fadeOut(200);
    }
});

$(function () {

    new Main();

})
